package com.junyuan.bletooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btn, btn1;
    MyBroadcaseReceiver MyBroadcaseReceiver;
    Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            Bundle bundle=message.getData();
            String data=bundle.getString("data");

            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        btn1 = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
        btn1.setOnClickListener(this);

        MyBroadcaseReceiver =new MyBroadcaseReceiver();
        IntentFilter filter = new IntentFilter("BackData");
        registerReceiver(MyBroadcaseReceiver, filter);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                Toast.makeText(MainActivity.this, "发送链接蓝牙的广播", Toast.LENGTH_SHORT).show();
                Log.d("123", "发送链接蓝牙的广播");
                Intent intent = new Intent();
                intent.setAction("linkble");
                sendBroadcast(intent);
                break;
            case R.id.button1:
                MyApplication.instance.sendData("蓝牙命令", 100);
                break;
        }
    }


    class MyBroadcaseReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String backData = intent.getStringExtra("BackData");
            Log.d("mytag", "MoreMusicActivity的广播接收到：" + backData);
            Message msg=new Message();
            Bundle bundle=new Bundle();
            bundle.putString("data",backData);
            msg.setData(bundle);
            mHandler.sendMessage(msg);
        }
    }


}
